from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.views.generic import DetailView, UpdateView

from zanhu02.users.models import User


class UserDetailView(LoginRequiredMixin, DetailView):

    model = User
    template_name = 'users/user_detail.html'
    slug_field = "username"
    slug_url_kwarg = "username"  # 对应url中的路由的关键字参数

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data()
        user = User.objects.get(username=self.request.user.username)
        # 动态数量
        context["moments_num"] = user.publisher.filter(reply=False).count()

        # 文章数量
        context["article_num"] = user.author.filter(status="P").count()

        # 评论 = 动态评论 + 文章评论
        context["comment_num"] = user.publisher.filter(reply=True).count() + user.comment_comments.all().count()

        # 提问数量
        context["question_num"] = user.q_author.all().count()

        # 回答数量
        context["answer_num"] = user.a_author.all().count()

        # 我发送私信给了多少不同的用户
        tmp = set()
        sent_num = user.sent_message.all()
        for s in sent_num:
            tmp.add(s.recipient.username)
        # 我接受所有私信来自多少不同的用户
        received_num=user.received_message.all()
        for r in received_num:
            tmp.add(r.sender.username)
        # 取他们的交集

        # 互动数量 = 动态点赞数+问答点赞数+评论数+私信用户数(双方的互发)
        context["interaction_num"] = user.liked_news.all().count() + user.qa_vote.all().count() + \
                                     context["comment_num"] + len(tmp)
        return context


class UserUpdateView(LoginRequiredMixin, UpdateView):
    """用户只能更改自己的信息"""

    model = User
    template_name = 'users/user_form.html'
    fields = ["nickname","email","job_title","introduction","picture","location",
              "person_url","weibo","zhihu","github","linkedin"]


    def get_success_url(self):
        "更新成功后,跳转的页面"
        return reverse("users:detail", kwargs={"username": self.request.user.username})

    def get_object(self,queryset=None):
        return self.request.user


